import React from 'react';
import { connect } from 'dva';
import { Form, Drawer, Tag, Icon, Button, Row, Col, Input, TreeSelect, Switch, Tabs } from 'antd';
import styles from '@/pages/KnowledgeManagement/Overview/EditingKnowledge/editingStyle.less';
import ApiAndSlotReadOnly from '@/pages/KnowledgeManagement/Overview/EditingKnowledge/apiAndSlotReadOnly';
import SimilarQuestionReadOnly from '@/pages/KnowledgeManagement/Overview/EditingKnowledge/similarQuestionReadOnly';
import AnswerBackReadOnly from '@/pages/KnowledgeManagement/Overview/EditingKnowledge/answerBackReadOnly';
import AnswerUtils from "@/utils/answerUtils/answerUtils";
const { TreeNode } = TreeSelect;

class KnowledgeReadOnly extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      title: '知识点详情',
      qaId: null,
      categoryValue: '',
      categoryList: [],
      slotData: [],
      apiData: {},
      apiAndSlotData: [],
      stdQuestion: '',
      similarQuestions: [],
      isShowSecondDrawer: false,
      answerArr: [],
      relatedData: [],
      knowledgeDisable: true,
      dataDetail: null,
    }
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this);
    }
  }

  /**
   * 修改记录页打开的详情，已返回json，无需调用详情接口
   */
  setValueByDataJson = (dataJson) => {
    let data = dataJson;
    data.apiId = null;
    data.apiData = dataJson.apiJson;
    data.categoryName = dataJson.categoryName;
    this.setState({ visible: true, title: '知识点详情', dataDetail: dataJson }, () => {
      this.renderDetailData(dataJson);
    })
  }

  showEditDrawer = (row, question, categoryId) => {
    this.fetchCategory();
    this.setState({ visible: true, title: '知识点详情', qaId: row.id ? row.id : row.qaId, categoryValue: categoryId }, () => {
      this.getKnowledgeDetail(row.id ? row.id : row.qaId);
    })
  }

  fetchCategory() {
    const { dispatch } = this.props;
    dispatch({
      type: 'editingKnowledge/getCategoryKnowledge',
      payload: {},
      callback: res => {
        // console.log(res);
        let tree = [];
        if (res && res[0]) {
          tree.push(res[0]);
          this.setState({ categoryList: tree })
        }
      },
    });
  }

  getKnowledgeDetail = id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'editingKnowledge/fetchKnowledgeDetail',
      payload: { id },
      callback: res => {
        // console.log(res);
        this.renderDetailData(res)
      },
    });
  }

  /**
   * 根据详情数据来渲染页面
   */
  renderDetailData = res => {
    this.setState({
      slotData: res.slotList ? res.slotList : [],
      apiAndSlotData: res.slotAndApi ? res.slotAndApi : [],
      answerArr: res.answers,
      relatedData: res.relQas ? res.relQas : [],
      categoryValue: res.categoryName ? res.categoryName : res.categoryId,
      knowledgeDisable: !res.disabled,
      apiData: res.apiData ? res.apiData : {}
    }, () => {
      //v2版本答案改版
      this.AnswerUtils.setAnswers(res.answers.defaultAnswer);
      this.SimilarQuestion.setStandQuestion(res.basicQuestion);
      this.SimilarQuestion.setQuestions(res.questions ? res.questions : []);
      if (res.apiId) {
        this.setApiData({ id: res.apiId })
      }
    })
  }

  setApiData = (data) => {
    // console.log(data);
    const { dispatch } = this.props;
    let obj = {};
    dispatch({
      type: 'editingKnowledge/doApiDetailById',
      payload: { id: data.id },
      callback: res => {
        // console.log(res);
        if (res) {
          obj = res;
          this.setState({ apiData: obj })
        }
      },
    });
  }

  showMoreQuestionDrawer = (similarQuestions, stdQuestion) => {
    this.setState({ isShowSecondDrawer: true, similarQuestions, stdQuestion })
  }

  renderTree = data => {
    return data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.name} key={item.id} value={item.id} id={item.id}>{this.renderTree(item.children)}</TreeNode>
        );
      };
      return <TreeNode title={item.name} key={item.id} value={item.id} id={item.id} />;
    })
  }

  onClose = () => {
    this.AnswerUtils.clearInitData()
    this.setState({
      visible: false,
      similarQuestions: [],
      qaId: '',
      categoryValue: '',
      relatedData: [],
      isForever: true,
      from: '',
      to: '',
      knowledgeDisable: true,
      slotData: [],
      apiAndSlotData: [],
      apiData: {}
    })
  }

  closeMoreQuestionDrawer = () => {
    let data = this.SimilarQuestionMore.state.moreQuestions;
    let stdQuestion = this.SimilarQuestionMore.getStdQuestionForSecondDrawer();
    this.setState({ similarQuestions: data, isShowSecondDrawer: false, }, () => {
      this.SimilarQuestion.setQuestions(data);
      this.SimilarQuestion.setStandQuestion(stdQuestion)
    })
  }

  createKnowledge = () => {
    const { dataDetail } = this.state;
    this.onClose();
    this.props.openCreateModal(dataDetail.basicQuestion, dataDetail.questions)
  }

  render() {
    const {
      title, visible, slotData, apiData, apiAndSlotData, stdQuestion, similarQuestions,
      isShowSecondDrawer, answerArr, relatedData, categoryList, categoryValue, knowledgeDisable
    } = this.state;
    const { pageSource, form } = this.props;
    const robotName = (pane) => {
			if (pane.robotName !== '系统答案') {
				return pane.robotName;
			} else {
				return '默认所有应用';
			}
		};

    return (
      <Drawer title={title} placement="right" closable onClose={this.onClose} visible={visible} width={800} destroyOnClose>
        {pageSource && pageSource === 'answerDetailStatis' ? null : (
          <div style={{ textAlign: 'right' }}>
            <Button size={'small'} type={'primary'} onClick={this.createKnowledge}>创建知识点</Button>
          </div>
        )}
        {slotData && slotData.length > 0 ? (
          <div style={{ margin: '10px 0px' }}>
            <h3 className={styles.hTitle}>词槽</h3>
            {slotData.map(item => {
              return (
                <Tag style={{ margin: '0px 10px' }} key={item.id} closable={false}>
                  &lt;{item.name}&gt;-{item.key ? item.key : item.keyName}
                </Tag>
              )
            })}
          </div>
        ) : null}
        {apiData && Object.keys(apiData).length > 0 ? (
          <div style={{ margin: '10px 0px' }}>
            <h3 className={styles.hTitle}>API接口</h3>
            <div>触发知识点时调用接口 <Tag closable={false} style={{ margin: '0px 10px' }}>{apiData.name}</Tag> </div>
            {apiData && slotData && slotData.length > 0 && Object.keys(apiData).length > 0 ? (
              <ApiAndSlotReadOnly slotData={slotData} apiData={apiData} apiAndSlotData={apiAndSlotData} />
            ) : null}
          </div>
        ) : null}
        <div>
          <h3 className={styles.hTitle} style={{ overflow: 'hidden' }}>
            <Col span={12} style={{ padding: 0 }}>问题</Col>
          </h3>
          <SimilarQuestionReadOnly
            showMoreQuestion={this.showMoreQuestionDrawer}
            secondDrawer={isShowSecondDrawer}
            similarQuestionsList={similarQuestions}
            onRef={ref => this.SimilarQuestion = ref}
            stdQuestion={stdQuestion}
            slotData={slotData}
          />
        </div>
        <div>
          <h3 className={styles.hTitle}>答案</h3>
          <div style={{ width: '100%', margin: '0 auto', marginBottom: 10 }}>
            <Form>
              <AnswerUtils form={form} onRef={ref => this.AnswerUtils = ref} hasRefer={false} disabled={true} />
            </Form>
            {answerArr && answerArr.length > 0 ? (
              <Tabs defaultActiveKey={'default'}>
                {answerArr.map((item, index) => {
                  return (
                    <Tabs.TabPane key={item.robotId} tab={robotName(item)}>
                      {item.answers.map((answer, answerIndex) => {
                        return (
                          <div style={{ margin: '10px 0' }} key={answerIndex}>
                            <AnswerBackReadOnly onRef={ref => this.AnswerBack = ref} answer={answer} index={answerIndex} />
                          </div>
                        )
                      })}
                    </Tabs.TabPane>
                  )
                })}
              </Tabs>
            ) : null}
          </div>
        </div>
        <div style={{ margin: "10px 0" }}>
          <h3 className={styles.hTitle} style={{ overflow: 'hidden' }}>
            <Col span={12} style={{ padding: 0 }}>关联问题</Col>
          </h3>
          <div style={{ width: 520, margin: '0 auto', marginBottom: 10 }}>
            {relatedData.map((item, index) => {
              return (
                <div key={item.id} style={{ margin: '10px 0' }}>
                  <Input disabled={true} value={item.basicQuestion} style={{ width: '80%' }} />
                </div>
              )
            })}
          </div>
        </div>
        <div style={{ marginBottom: 10 }}>
          <h3 className={styles.hTitle}>知识点相关</h3>
          <div style={{ width: 500, margin: '0 auto' }}>
            <label>选择分类：</label>
            <TreeSelect
              style={{ width: '80%' }}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              placeholder="请选择分类"
              allowClear
              showSearch
              showCheckedStrategy="SHOW_PARENT"
              treeNodeFilterProp="title"
              value={categoryValue}
              disabled={true}
            >
              {this.renderTree(categoryList)}
            </TreeSelect>
          </div>

        </div>
        <div style={{ marginBottom: 60 }}>
          <h3 className={styles.hTitle}>生效时间</h3>
          <div style={{ width: 500, margin: '0 auto' }}>
            <div>
              <label>知识点状态：</label>
              <Switch checkedChildren="启用" unCheckedChildren="停用" checked={knowledgeDisable} disabled={true} />
            </div>
          </div>
        </div>
        <Drawer
          title={'更多相似问'}
          placement="right"
          closable
          onClose={this.closeMoreQuestionDrawer}
          visible={isShowSecondDrawer}
          width={700}
          destroyOnClose
        >
          <SimilarQuestionReadOnly
            showMoreQuestion={this.showMoreQuestionDrawer}
            secondDrawer={isShowSecondDrawer}
            similarQuestionsList={similarQuestions}
            onRef={ref => this.SimilarQuestionMore = ref}
            stdQuestion={stdQuestion}
            slotData={slotData}
          />
        </Drawer>
      </Drawer>
    )
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(KnowledgeReadOnly));
